//
//  ChatContent.m
//  安好
//
//  Created by lianchuang on 14/10/30.
//  Copyright (c) 2014年 冯凯. All rights reserved.
//

#import "ChatContent.h"

@implementation ChatContent
- (id)initWithQid:(NSString *)qid AndMyuid:(NSString *)myuid AndMessageType:(NSString *)messageType AndMessageDirection:(NSString *)messageDirection AndAction:(NSString *)action AndDateLine:(NSString *)dateline AndMessage:(NSString *)message AndPic:(NSString *)pic AndType:(NSString *)type AndUid:(NSString *)uid AndUsername:(NSString *)username AndVoice:(NSString *)voice AndVoiceLength:(NSString *)voicelence AndDepartmentName:(NSString *)departmentname AndIsQuestion:(NSString *)isQuestion AndMethod:(NSString *)method AndWidth:(NSString *)width AndHeigth:(NSString *)heigth AndShowTime:(NSString *)showTime AndSuccess:(NSString *)success
{
    if (self=[super init]) {
        self.qid=qid;
        self.myuid=myuid;
        self.messageType=messageType;
        self.messageDirection=messageDirection;
        self.action=action;
        self.dateline=dateline;
        self.message=message;
        self.pic=pic;
        self.type=type;
        self.uid=uid;
        self.username=username;
        self.voice=voice;
        self.voicelength=voicelence;
        self.isQuestion=isQuestion;
        self.departmentname=departmentname;
        self.method=method;
        self.width=width;
        self.heigth=heigth;
        self.showTime=showTime;
        self.success=success;
    }
    return self;
}
/**
 *  
 聊天信息插入数据库
 *
 *  @param message 聊天的基本信息
 *
 *  @return 是否插入成功
 */
+ (BOOL)insertChatMessageItem:(id)message Andsuccess:(NSString *)success AndMessageDirection:(NSString *)index
{
    NSDictionary *dict;
    if ([index isEqualToString:@"2"]) {
        dict = [YXJSON dictionaryOrArrayWithJSONSString:message];
    }
    else {
        dict=(NSDictionary *)message;
    }
    NSString * sql = [NSString stringWithFormat:@"insert into ChatContent (qid, myuid, messageType, messageDirection, action, dateline, message, pic, type, uid, username, voice, voicelength, departmentname, isQuestion, method,width,height,showTime,success,imageData,voiceData,date) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?,?,?,?,?,?,?)"];
    NSUserDefaults *userDefaults= [NSUserDefaults standardUserDefaults];
    NSString * myuid = [userDefaults objectForKey:@"SelfUidKey"];
    FMDatabase *db=[MyFMDB openDB];

    NSString *qid=[dict valueForKey:@"qid"];
    NSString *uid=[dict valueForKey:@"uid"];
    NSString *dateline;
    if ([index isEqualToString:@"2"]) {
        dateline=[dict valueForKey:@"dateline"];
    }else
    {
        dateline=[NSString stringWithFormat:@"%.f", [[NSDate date] timeIntervalSince1970]*10000];
    }
//    NSString *dateline = [dict valueForKey:@"dateline"];
    NSString *date;
    NSString *dateStr=[NSString stringWithFormat:@"%@",[dict valueForKey:@"dateline"]];
    if ([dateStr length]>0) {
        date=dateStr;
    }else
    {
        date=@"0";
    }
    //判断消息方向
    NSString *messageDirection = index;
    NSString *messageType;
    NSString *chatMessage;
    if ([[dict valueForKey:@"message"] length] > 0) {
        messageType = @"1";
        chatMessage=[dict valueForKey:@"message"];
    } else if ([[dict valueForKey:@"pic"] length] > 0) {
        messageType = @"2";
//        chatMessage = @"[图片]";
    } else {
        messageType = @"3";
//        chatMessage = @"[语音]";
    }
    
    NSString *action=[dict valueForKey:@"action"];
    NSString *type=[dict valueForKey:@"type"];
    NSString *username=[dict valueForKey:@"username"];
    NSString *voice=[dict valueForKey:@"voice"];
    NSString *voicelength=[dict valueForKey:@"voicelength"];
    NSString *isQuestion=[dict valueForKey:@"isQuestion"];
    //如果是别人的回复，别人的图片读取url，messageDirection=2;自己发出的信息messageDirection=1，自己发的图片读取本地
    NSData *imageData;
    NSString *pic;
    NSString *departmentname;

    NSData *voiceData;
    if ([messageDirection isEqualToString:@"1"]&&[messageType isEqualToString:@"2"]) {
        imageData=[dict valueForKey:@"imageData"];
        pic=@"";
    }else if([messageDirection isEqualToString:@"1"]&&[messageType isEqualToString:@"3"])
    {
        voiceData=[dict valueForKey:@"voiceData"];
    }
    else
    {
        imageData=nil;
        pic=[dict valueForKey:@"pic"];
    }
//    __block CGSize size;
    NSString *width=[dict valueForKey:@"width"];
    NSString *heigth=[dict valueForKey:@"heigth"];
    //判断是否是咨询问题详情，如果是，需要特殊排版。
    if ([isQuestion isEqualToString:@"1"]) {
        departmentname=[dict valueForKey:@"departmentname"];
    }else
    {
        departmentname=@"";
        if (pic.length>0) {
            if (width>0) {
            }else
            {
            }
        }
    }
    NSString *method=[dict valueForKey:@"method"];
    NSString *showTime=@"";
    //得判断是否发送成功（先展示数据，若未发送成功，出现重新发送按钮）；
    NSString *successType=success;
    // fmdb数据库的sql语句中 t的所有参数要求是对象类型
    BOOL successM=[db executeUpdate:sql, qid, myuid, messageType, messageDirection, action, dateline, chatMessage, pic, type, uid, username, voice, voicelength, departmentname, isQuestion,method,width,heigth,showTime,successType,imageData,voiceData,date];
    [db close];
    return successM;
}
/**
 *  读取医患咨询数据，根据qid取 (从聊天内容表里)
 *
 *  @param 从聊天内容表里 取出聊天信息
 *
 *  @return 返回消息的数组
 */

+(NSMutableArray *)readItemFromChatContentTable:(NSInteger)index count:(NSInteger)count withQid:(NSString *)qid
{
    FMDatabase *db=[MyFMDB openDB];
    //判断是否有转诊字段，如果有就设置为yes，并且插入到数据的第一条
    BOOL isreferral = NO;
    //    NSString * sql = [NSString stringWithFormat:@"select * from ChatContentTable where qid = %@ limit %d, %d", qid, index, count];
    NSUserDefaults *userDefaults= [NSUserDefaults standardUserDefaults];
    NSString * uid = [userDefaults objectForKey:@"SelfUidKey"];
    NSString *sql = [NSString stringWithFormat:@"select * from (select * from ChatContent where qid = %@ and myuid = %@ order by rowid desc) limit %ld, %ld", qid, uid, index, count];
    FMResultSet * rs = [db executeQuery:sql];
    NSMutableArray * array = [NSMutableArray arrayWithCapacity:0];

    while([rs next])
    {
        // 如果有值
        ChatContent * chatContent = [[ChatContent alloc] init];
        chatContent.qid = [rs stringForColumn:@"qid"];
        chatContent.messageType = [rs stringForColumn:@"messageType"];
        chatContent.messageDirection = [rs stringForColumn:@"messageDirection"];
        chatContent.action = [rs stringForColumn:@"action"];
        chatContent.dateline = [rs stringForColumn:@"dateline"];
        chatContent.message = [rs stringForColumn:@"message"];
        chatContent.pic = [rs stringForColumn:@"pic"];
        chatContent.type = [rs stringForColumn:@"type"];
        chatContent.uid = [rs stringForColumn:@"uid"];
        chatContent.username = [rs stringForColumn:@"username"];
        chatContent.voice = [rs stringForColumn:@"voice"];
        chatContent.voicelength = [rs stringForColumn:@"voicelength"];
        chatContent.departmentname = [rs stringForColumn:@"departmentname"];
        chatContent.isQuestion = [rs stringForColumn:@"isQuestion"];
        chatContent.method = [rs stringForColumn:@"method"];
        chatContent.width = [rs stringForColumn:@"width"];
        chatContent.heigth = [rs stringForColumn:@"height"];
        chatContent.showTime = [rs stringForColumn:@"showTime"];
        chatContent.success=[rs stringForColumn:@"success"];
        chatContent.imageData=[rs dataForColumn:@"imageData"];
        chatContent.voiceData=[rs dataForColumn:@"voiceData"];
        chatContent.isreferral=[rs stringForColumn:@"isreferral"];
        if ([chatContent.isreferral isEqualToString:@"1"]) {
            isreferral=YES;
            [array insertObject:chatContent atIndex:0];
        }else
        {
            if (isreferral==YES) {
                [array insertObject:chatContent atIndex:1];
            }else
            {
               [array insertObject:chatContent atIndex:0];
            }
            
        }
    }
    [db close];
    
    return array;
}
/**
 *  读取普通客户（用户）之间聊天数据 （聊天页面；聊天表）
 *
 *  @param 从聊天内容表里 聊天信息
 *
 *  @return 信息数组
 */
+(NSMutableArray *)readItemFromChatContentTable:(NSInteger)index count:(NSInteger)count withUid:(NSString *)uid
{
    FMDatabase *db=[MyFMDB openDB];
    NSUserDefaults *userDefaults= [NSUserDefaults standardUserDefaults];
    NSString * uid1 = [userDefaults objectForKey:@"SelfUidKey"];
    NSString *sql = [NSString stringWithFormat:@"select * from ChatContent where uid = %@ and myuid = %@ order by rowid desc limit %ld, %ld", uid, uid1, index, count];
    FMResultSet * rs = [db executeQuery:sql];
    NSMutableArray * array = [NSMutableArray arrayWithCapacity:0];
    while([rs next])
    {
        // 如果有值
        ChatContent * chatContent = [[ChatContent alloc] init];
        chatContent.qid = [rs stringForColumn:@"qid"];
        chatContent.messageType = [rs stringForColumn:@"messageType"];
        chatContent.messageDirection = [rs stringForColumn:@"messageDirection"];
        chatContent.action = [rs stringForColumn:@"action"];
        chatContent.dateline = [rs stringForColumn:@"dateline"];
        chatContent.message = [rs stringForColumn:@"message"];
        chatContent.pic = [rs stringForColumn:@"pic"];
        chatContent.type = [rs stringForColumn:@"type"];
        chatContent.uid = [rs stringForColumn:@"uid"];
        chatContent.username = [rs stringForColumn:@"username"];
        chatContent.voice = [rs stringForColumn:@"voice"];
        chatContent.voicelength = [rs stringForColumn:@"voicelength"];
        chatContent.departmentname = [rs stringForColumn:@"departmentname"];
        chatContent.isQuestion = [rs stringForColumn:@"isQuestion"];
        chatContent.width = [rs stringForColumn:@"width"];
        chatContent.heigth = [rs stringForColumn:@"height"];
        chatContent.showTime = [rs stringForColumn:@"showTime"];
        chatContent.imageData=[rs dataForColumn:@"imageData"];
        chatContent.success=[rs stringForColumn:@"success"];
        [array insertObject:chatContent atIndex:0];
    }
    [db close];
    return array;
}
/**
 *  医患之间聊天记录，患患之间聊天，若发送成功，修改发送状态
 *
 *  @param index 要发送数据当前位置
 *  @param count 展示聊天数据的个数
 *  @param qid   咨询qid
 *
 *  @return yes or no
 */
- (BOOL)resetChatContentSuccessStatus:(NSInteger)index count:(NSInteger)count withQid:(NSString *)qid
{
    FMDatabase *db=[MyFMDB openDB];
    NSUserDefaults *userDefaults= [NSUserDefaults standardUserDefaults];
    NSString * uid1 = [userDefaults objectForKey:@"SelfUidKey"];
    NSString * sql = [NSString stringWithFormat:@"update (select * from ChatContent where qid = %@ and myuid = %@ order by dateline desc) set success = 1 limit %ld, %ld", qid,uid1,index,count];
    BOOL success=[db executeUpdate:sql];
    [db close];
    return success;
}
/**
 *  患患之间聊天，若发送成功，修改发送状态
 *
 *  @param index 要发送数据当前位置
 *  @param count 展示聊天数据的个数
 *  @param uid   对方的uid
 *
 *  @return YES or NO
 */
- (BOOL)resetChatContentSuccessStatus:(NSInteger)index count:(NSInteger)count withUid:(NSString *)uid
{
    FMDatabase *db=[MyFMDB openDB];
    NSUserDefaults *userDefaults= [NSUserDefaults standardUserDefaults];
    NSString * uid1 = [userDefaults objectForKey:@"SelfUidKey"];
    NSString * sql = [NSString stringWithFormat:@"update (select * from ChatContent where uid = %@ and myuid = %@ order by dateline desc) set success = YES limit %ld, %ld",uid,uid1,index,count];
    BOOL success=[db executeUpdate:sql];
    [db close];
    return success;
}
//- (BOOL)resendChatMessage:(NSInteger)index count:(NSInteger)count withUid:(NSString *)uid
//{}
//- (BOOL)resendChatMessage:(NSInteger)index count:(NSInteger)count withQid:(NSString *)qid
//{}
/**
 *  获取聊天页面，收到的消息的最新时间，传给服务器。
 *
 *  @return date
 */
+ (NSString *)readTheLastDate;
{
    FMDatabase *db=[MyFMDB openDB];
    NSUserDefaults *userDefaults= [NSUserDefaults standardUserDefaults];
    NSString * uid = [userDefaults objectForKey:@"SelfUidKey"];
    NSString * sql = [NSString stringWithFormat:@"select * from ChatContent where myuid = %@ order by date desc  limit 0,1", uid];
    FMResultSet *rs=[db executeQuery:sql];
    NSString *NewDate;
    while ([rs next]) {
        NewDate=[rs stringForColumn:@"date"];
    }
    [db close];
    return NewDate;
}
+ (BOOL)insertFirstIndex:(NSDictionary *)dict
{
    FMDatabase *db=[MyFMDB openDB];

    if (![self isreferral:[dict valueForKey:@"qid"] AndDb:db]) {
        NSString * sql = [NSString stringWithFormat:@"insert into ChatContent (qid, myuid, messageDirection, messageType,message,action, dateline, pic, type, uid, username, voice, voicelength, departmentname, isQuestion, method,width,height,showTime,success,imageData,voiceData,date,isreferral) values (?, ?, ?, ?, ?,?, ?, ?, ?, ?,?,?, ?, ?, ?, ?,?,?,?,?,?,?,?,?)"];
        NSUserDefaults *userDefaults= [NSUserDefaults standardUserDefaults];
        NSString * myuid = [userDefaults objectForKey:@"SelfUidKey"];
        
        NSString *qid=[dict valueForKey:@"qid"];
        NSString *uid=[dict valueForKey:@"uid"];
        NSString *dateline;
        dateline=@"0";
        NSString *date=@"0";
        
        //判断消息方向
        NSString *messageDirection = @"2";
        NSString *messageType;
        NSString *chatMessage;
        if ([[dict valueForKey:@"message"] length] > 0) {
            messageType = @"1";
            chatMessage=[NSString stringWithFormat:@"该问题已被转至%@医生为您解答！",[dict valueForKey:@"doctorname"]];
        } else if ([[dict valueForKey:@"pic"] length] > 0) {
            messageType = @"2";
            //        chatMessage = @"[图片]";
        } else {
            messageType = @"3";
            //        chatMessage = @"[语音]";
        }
        
        NSString *action=@"";
        NSString *type=@"0";
        NSString *username=[dict valueForKey:@"doctorname"];
        NSString *voice=@"";
        NSString *voicelength=@"";
        NSString *isQuestion=@"";
        //如果是别人的回复，别人的图片读取url，messageDirection=2;自己发出的信息messageDirection=1，自己发的图片读取本地
        
        NSString *method=@"";
        NSString *showTime=@"";
        //得判断是否发送成功（先展示数据，若未发送成功，出现重新发送按钮）；
        NSString *successType=@"1";
        NSString *pic=@"";
        NSString *departmentname=@"0";
        NSString *width=@"0";
        NSString *heigth=@"0";
        NSData *imageData=[NSData data];
        NSData *voiceData=[NSData data];
        NSString *isreferral=@"1";
//        NSArray *arr=@[qid, myuid, messageDirection, chatMessage,action, dateline, pic, type, uid, username, voice, voicelength, departmentname, isQuestion,method,width,heigth,showTime,successType,imageData,voiceData,date,isreferral];
        // fmdb数据库的sql语句中 t的所有参数要求是对象类型
        BOOL successM=[db executeUpdate:sql, qid, myuid, messageDirection, messageType,chatMessage,action, dateline, pic, type, uid, username, voice, voicelength, departmentname, isQuestion,method,width,heigth,showTime,successType,imageData,voiceData,date,isreferral];
        [db close];
        return successM;
    }else{
        return NO;
    }
}
+ (BOOL)isreferral:(NSString *)qid AndDb:(FMDatabase *)dataBase
{
    NSString * sql = [NSString stringWithFormat:@"select * from ChatContent where qid = ?and isreferral=1"];
    FMResultSet * rs = [dataBase executeQuery:sql, qid];
    if([rs next])
    {
        // 如果有值
        return YES;
    }
    return NO;
}
#pragma mark -更新图片高度
+ (void)updateImageHeigth:(NSString *)height withWidth:(NSString *)width withImageURl:(NSString *)url
{
    FMDatabase *db=[MyFMDB openDB];
    NSString * sql = [NSString stringWithFormat:@"update ChatContent set height=?,width=? where pic = ?"];
    BOOL successM= [db executeUpdate:sql,height,width,url];
//    MyNSLog("%@---%@",[db lastErrorMessage],[db lastError]);
}
#pragma mark - 异步算图片尺寸
+(CGSize)downloadImageSizeWithURL:(id)imageURL
{
    NSURL* URL = nil;
    if([imageURL isKindOfClass:[NSURL class]]){
        URL = imageURL;
    }
    if([imageURL isKindOfClass:[NSString class]]){
        URL = [NSURL URLWithString:imageURL];
    }
    if(URL == nil)
        return CGSizeZero;
    
    NSString* absoluteString = URL.absoluteString;
    
#ifdef dispatch_main_sync_safe
    if([[SDImageCache sharedImageCache] diskImageExistsWithKey:absoluteString])
    {
        UIImage* image = [[SDImageCache sharedImageCache] imageFromMemoryCacheForKey:absoluteString];
        if(!image)
        {
            NSData* data = [[SDImageCache sharedImageCache] performSelector:@selector(diskImageDataBySearchingAllPathsForKey:) withObject:URL.absoluteString];
            image = [UIImage imageWithData:data];
        }
        if(!image)
        {
            return image.size;
        }
    }
#endif
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:URL];
    NSString* pathExtendsion = [URL.pathExtension lowercaseString];
    
    CGSize size = CGSizeZero;
    if([pathExtendsion isEqualToString:@"png"]){
        size =  [self downloadPNGImageSizeWithRequest:request];
    }
    else if([pathExtendsion isEqual:@"gif"])
    {
        size =  [self downloadGIFImageSizeWithRequest:request];
    }
    else{
        size = [self downloadJPGImageSizeWithRequest:request];
    }
    if(CGSizeEqualToSize(CGSizeZero, size))
    {
        NSData* data = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:URL] returningResponse:nil error:nil];
        UIImage* image = [UIImage imageWithData:data];
        if(image)
        {
#ifdef dispatch_main_sync_safe
            [[SDImageCache sharedImageCache] storeImage:image recalculateFromImage:YES imageData:data forKey:URL.absoluteString toDisk:YES];
#endif
            size = image.size;
        }
    }
    return size;
}
+(CGSize)downloadPNGImageSizeWithRequest:(NSMutableURLRequest*)request
{
    [request setValue:@"bytes=16-23" forHTTPHeaderField:@"Range"];
    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if(data.length == 8)
    {
        int w1 = 0, w2 = 0, w3 = 0, w4 = 0;
        [data getBytes:&w1 range:NSMakeRange(0, 1)];
        [data getBytes:&w2 range:NSMakeRange(1, 1)];
        [data getBytes:&w3 range:NSMakeRange(2, 1)];
        [data getBytes:&w4 range:NSMakeRange(3, 1)];
        int w = (w1 << 24) + (w2 << 16) + (w3 << 8) + w4;
        int h1 = 0, h2 = 0, h3 = 0, h4 = 0;
        [data getBytes:&h1 range:NSMakeRange(4, 1)];
        [data getBytes:&h2 range:NSMakeRange(5, 1)];
        [data getBytes:&h3 range:NSMakeRange(6, 1)];
        [data getBytes:&h4 range:NSMakeRange(7, 1)];
        int h = (h1 << 24) + (h2 << 16) + (h3 << 8) + h4;
        return CGSizeMake(w, h);
    }
    return CGSizeZero;
}
+(CGSize)downloadGIFImageSizeWithRequest:(NSMutableURLRequest*)request
{
    [request setValue:@"bytes=6-9" forHTTPHeaderField:@"Range"];
    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if(data.length == 4)
    {
        short w1 = 0, w2 = 0;
        [data getBytes:&w1 range:NSMakeRange(0, 1)];
        [data getBytes:&w2 range:NSMakeRange(1, 1)];
        short w = w1 + (w2 << 8);
        short h1 = 0, h2 = 0;
        [data getBytes:&h1 range:NSMakeRange(2, 1)];
        [data getBytes:&h2 range:NSMakeRange(3, 1)];
        short h = h1 + (h2 << 8);
        return CGSizeMake(w, h);
    }
    return CGSizeZero;
}
+(CGSize)downloadJPGImageSizeWithRequest:(NSMutableURLRequest*)request
{
    [request setValue:@"bytes=0-209" forHTTPHeaderField:@"Range"];
    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    
    if ([data length] <= 0x58) {
        return CGSizeZero;
    }
    
    if ([data length] < 210) {// 肯定只有一个DQT字段
        short w1 = 0, w2 = 0;
        [data getBytes:&w1 range:NSMakeRange(0x60, 0x1)];
        [data getBytes:&w2 range:NSMakeRange(0x61, 0x1)];
        short w = (w1 << 8) + w2;
        short h1 = 0, h2 = 0;
        [data getBytes:&h1 range:NSMakeRange(0x5e, 0x1)];
        [data getBytes:&h2 range:NSMakeRange(0x5f, 0x1)];
        short h = (h1 << 8) + h2;
        return CGSizeMake(w, h);
    } else {
        short word = 0x0;
        [data getBytes:&word range:NSMakeRange(0x15, 0x1)];
        if (word == 0xdb) {
            [data getBytes:&word range:NSMakeRange(0x5a, 0x1)];
            if (word == 0xdb) {// 两个DQT字段
                short w1 = 0, w2 = 0;
                [data getBytes:&w1 range:NSMakeRange(0xa5, 0x1)];
                [data getBytes:&w2 range:NSMakeRange(0xa6, 0x1)];
                short w = (w1 << 8) + w2;
                short h1 = 0, h2 = 0;
                [data getBytes:&h1 range:NSMakeRange(0xa3, 0x1)];
                [data getBytes:&h2 range:NSMakeRange(0xa4, 0x1)];
                short h = (h1 << 8) + h2;
                return CGSizeMake(w, h);
            } else {// 一个DQT字段
                short w1 = 0, w2 = 0;
                [data getBytes:&w1 range:NSMakeRange(0x60, 0x1)];
                [data getBytes:&w2 range:NSMakeRange(0x61, 0x1)];
                short w = (w1 << 8) + w2;
                short h1 = 0, h2 = 0;
                [data getBytes:&h1 range:NSMakeRange(0x5e, 0x1)];
                [data getBytes:&h2 range:NSMakeRange(0x5f, 0x1)];
                short h = (h1 << 8) + h2;
                return CGSizeMake(w, h);
            }
        } else {
            return CGSizeZero;
        }
    }
}
+(id)diskImageDataBySearchingAllPathsForKey:(id)key
{
    return nil;
}

@end
